package com.learn.grpc.loadbalance;

import cn.hutool.core.thread.ThreadUtil;
import com.learn.grpc.grpc.LbServiceGrpc;
import com.learn.grpc.hello.PingRequest;
import com.learn.grpc.hello.PingResponse;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class LbMultiServiceClient {

    @Test
    public void loadBalanceTest() {

        // 注册命名服务解析器
        NameResolverRegistry.getDefaultRegistry().register(new LbNameProvider());
        // 注册负载策略
        LoadBalancerRegistry.getDefaultRegistry().register(new LbLoadBalancerProvider());

        //服务1
        ManagedChannel userServiceChannel = ManagedChannelBuilder
                .forTarget("lb://user-service")
                .defaultLoadBalancingPolicy("custom_round_robin")  // 自定义负载策略
                .usePlaintext()
                .build();

        //服务2
        ManagedChannel orderServiceChannel = ManagedChannelBuilder
                .forTarget("lb://order-service")
                .defaultLoadBalancingPolicy("custom_round_robin")  // 自定义负载策略
                .usePlaintext()
                .build();

        //2.构建客户端, 指定超时时间为 1s
        LbServiceGrpc.LbServiceBlockingStub userStub = LbServiceGrpc.newBlockingStub(userServiceChannel);

        LbServiceGrpc.LbServiceBlockingStub orderStub = LbServiceGrpc.newBlockingStub(orderServiceChannel);

        //3.发送多次请求

            new Thread(()->{
                for (int i = 0; i < 100; i++) {

                    PingRequest request = PingRequest.newBuilder()
                            .setContent("user_" + i)
                            .build();
                    PingResponse resp = userStub.ping(request);
                    System.out.println(String.format("code:%s, message:%s, data:%s", resp.getCode(), resp.getMessage(), resp.getData()));
                    ThreadUtil.sleep(1000);

                }
            }).start();

            new Thread(()->{
                for (int i = 0; i < 100; i++) {

                    PingRequest request1 = PingRequest.newBuilder()
                            .setContent("order_" + i)
                            .build();
                    PingResponse resp = orderStub.ping(request1);
                    System.out.println(String.format("code:%s, message:%s, data:%s", resp.getCode(), resp.getMessage(), resp.getData()));
                    ThreadUtil.sleep(1000);
                }
            }).start();

        ThreadUtil.sleep(Integer.MAX_VALUE);

    }


}
